import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { LoginService } from 'src/app/core/service/login.service';
import { AuthService } from 'src/app/core/auth/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  // 表单验证
  loginForm: FormGroup;
  msg: string;
  data: any;
  username = '';

  constructor(
    private router: Router,
    private activeRoute: ActivatedRoute,
    private message: NzMessageService,
    private loginservice: LoginService,
    private authService: AuthService,
    fb: FormBuilder
  ) {
    this.loginForm = fb.group({
      username: [null, Validators.compose([Validators.required, Validators.email])],
      password: [null, Validators.required],
    });
  }

  ngOnInit() {

  }

  getHome() {
    console.log('无权限，从此进入~~~');
    this.router.navigate(['/layout/monitor']);
  }

  goHome() {
    console.log(this.loginForm.controls);
    // tslint:disable-next-line:forin
    for (const c in this.loginForm.controls) {
      this.loginForm.controls[c].markAsTouched();
    }
    if (this.loginForm.valid) {
      this.loginservice.isLogin(this.loginForm.value.username, this.loginForm.value.password).subscribe((loginData) => {
        // this.data = loginData;
        if (loginData !== undefined) {
          this.authService.setCurrentUser(loginData);
          console.log('=== goHome.loginData() ===>', loginData);
          this.username = loginData.lastName;
          this.redirectToRouter(this.username);
        } else {
          this.errorMessage();
        }
      });
    } else {
      console.log('表单状态===>', this.loginForm.valid);
    }
  }
  errorMessage(): void {
    this.message.success('用户名或密码错误', { nzDuration: 10000 });
  }

  private redirectToRouter(username: string) {
    const prepareRedirectUrl = this.authService.getInitRedirectPageByRole();
    let redirectUrl = null;
    this.activeRoute.queryParams.subscribe((value) => {
      redirectUrl = value.redirectUrl ? decodeURIComponent(value.redirectUrl) : prepareRedirectUrl;
      this.router.navigate([redirectUrl], {
        queryParams: {
          username: username
        }
      })
        .then()
        .catch(e => {
          this.router.navigate([prepareRedirectUrl]);
        });
    });
  }
}
